import { defineStore } from "pinia";
import { loginFormData } from "@/views/login/interface/interface.ts";
import { userStoreInterface } from "@/pinia/modules/user/interface.ts";
import { fetchUserInfoAPI, loginAPI } from "@/api/user/user.ts";
import { getToken, removeToken, setToken } from "@/utils/cookie.ts";
import { Ref, ref } from "vue";
import { userInfoInterface } from "@/api/user/interface.ts";

const useUserStore = defineStore("user", (): userStoreInterface => {
  /* 用户的token */
  const tokenInfo: Ref<string> = ref<string>(getToken() || "");
  /* 用户的个人信息 */
  const userInfo: Ref<userInfoInterface> = ref<userInfoInterface>({ avatar: "", buttons: [], name: "", roles: [], routes: [] });
  /* 发送登录请求的回调函数 */
  const login: (formData: loginFormData) => Promise<string> = async (formData: loginFormData): Promise<string> => {
    const { data: token }: { data: string } = await loginAPI(formData);
    setToken(token);
    tokenInfo.value = token;
    return token;
  };
  /* 发送请求获取用户个人信息的回调函数 */
  const fetchUserInfo: () => Promise<any> = async (): Promise<any> => {
    const { data: user }: { data: userInfoInterface } = await fetchUserInfoAPI();
    userInfo.value = user;
    return user;
  };
  /* 用于退出登录的回调函数 */
  const logout: () => string = (): string => {
    userInfo.value = { avatar: "", buttons: [], name: "", roles: [], routes: [] };
    tokenInfo.value = "";
    removeToken();
    return "退出成功";
  };
  return {
    tokenInfo,
    userInfo,
    login,
    fetchUserInfo,
    logout,
  };
});

export default useUserStore;
